import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

function exportToJsonExcel(jsonData: any, fileName = 'export.xlsx') {
  const ws = XLSX.utils.json_to_sheet(jsonData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  // 生成一个二进制字符串  
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

  // 使用file-saver保存文件  
  saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), fileName);
}

// 将二进制字符串转换为ArrayBuffer  
function s2ab(s: string) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xFF;
  }
  return buf;
}

export default exportToJsonExcel;
